<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';

function getAccountInfo($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/sms/service/AccountService/getAccountInfo', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	if( $bodyArray['header']['desc'] == 'success' ) {
		if(is_array($bodyArray['body']['data'])) {
			$rquota   = isset($bodyArray['header']['rquota'])             ? $bodyArray['header']['rquota']              : 0;
			$userId   = isset($bodyArray['body']['data'][0]['userId'])    ? $bodyArray['body']['data'][0]['userId']     : 0;
			$balance  = isset($bodyArray['body']['data'][0]['balance'])   ? $bodyArray['body']['data'][0]['balance']    : 0;
			$budget   = isset($bodyArray['body']['data'][0]['budget'])    ? $bodyArray['body']['data'][0]['budget']     : 0;
			$userStat = isset($bodyArray['body']['data'][0]['userStat'])  ? $bodyArray['body']['data'][0]['userStat']   : 0;
			$database->query( " UPDATE cfg_expand SET `userStat` = '{$userStat}', `budget` = '{$budget}', `balance` = '{$balance}', `userRquota` = '{$rquota}', `userMessage` = '', `lastDatetime` = NOW() WHERE userid = {$userId} ");
		}
	} else {
		$userMessage = serialize(isset( $bodyArray['header']['failures'][0]) ?  $bodyArray['header']['failures'][0] : []);
		$database->query( " UPDATE cfg_expand SET `userStat` = 888,  `userRquota` = 0, `userMessage` = '{$userMessage}', `lastDatetime` = NOW() WHERE username = '{$user['username']}' ");
	}
	
	$getTargetPackageList = [
		'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
		'body'=>[
			'targetPackageTypeFields' =>	[ "ocpcBid"],
			'ids' =>	[ 1	],
			'level' => 1
	]];

	$getOcpcService = HttpPost('https://api.baidu.com/json/sms/service/OcpcService/getTargetPackageList', json_encode($getTargetPackageList));
	if($getOcpcService) {
	    $response = json_decode($getOcpcService, true);
	    if($response['header']['desc'] == 'success') {
	        if(isset($response['body']['data'][0]['ocpcBid'])) {
	            $database->query( " UPDATE cfg_expand SET `ocpcBid` = '{$response['body']['data'][0]['ocpcBid']}' WHERE username = '{$user['username']}' ");
	        }
	    }
	}
	
}

run(function() use ($argv) {
	showMessage('读取百度竞价账号数据.' );

    $config = getConfig();
    $database = new MySQL();
    $connect = $database->connect($config);
    if( $connect === false) {
    	return;
    }
    
    $userList = $database->query('SELECT `id`, `companyId`, `rebate`, `bazaarId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType = 1');
    if ($userList === false) {
    	showMessage($database->errno . ' - ' . $database->error);
    	return;
    }
    
    $userArray = array_chunk($userList, $config['curlnumber']);
    foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'读取百度竞价账号数据.' );
				getAccountInfo(json_encode([
					'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token']],
					'body'=> [
						"accountFields"=> [
							"userId",
							"cid",
							"balance",
							"pcBalance",
							"budget",
							"budgetType",
							"budgetOfflineTime",
							"cost",
							"excludeIp",
							"openDomains",
							"payment",
							"regDomain",
							"regionTarget",
							"userStat",
							"userLevel"
						]
					]
				]), $database, $user);
			});
		}
		Swoole\Coroutine::sleep(0.5);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');